<template>
  <div class="dashboard-container">
    <!-- 标题部分 -->
    <div class="title-container" style="display: flex; justify-content: center; align-items: center;">
      <div class="title" style="font-size: 30px;">
        <svg-icon icon-class="exam" style="font-size: 50px; margin-right: 10px;" />
        考试中心
      </div>
    </div>

    <!-- 添加图片走马灯 -->
    <div class="carousel">
      <div class="carousel-inner" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
        <div class="carousel-item" v-for="(image, index) in images" :key="index" :class="{ active: index === currentIndex }">
          <img :src="image.src" :alt="image.alt">
        </div>
      </div>
      <a class="carousel-control-prev" @click="prevSlide" href="#carouselExampleControls" role="button" data-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="sr-only"></span>
      </a>
      <a class="carousel-control-next" @click="nextSlide" href="#carouselExampleControls" role="button" data-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="sr-only"></span>
      </a>
    </div>

    <!-- 日历和试卷列表的容器 -->
    <div class="content-container">
      <!-- 日历部分 -->
      <div class="calendar-container" v-if="isDataLoaded">
        <div class="calendar-title" >
          <h2>考试时间安排</h2>
        </div>
        <el-calendar v-model="value">
        <template v-slot:dateCell="{ date, data }">
          <div :class="{ 'marked': isMarked(date) }" 
              @mouseenter="showExams = getExamsForDate(date)" 
              @mouseleave="showExams = ''">
            <span>{{ data.day.split('-').slice(1).join('-') }}</span>
            <span v-if="isMarked(date)" style="display: block; color: red; font-weight: bold;">本日有截止作答的考试</span>
            <div v-if="showExams" class="exams-tooltip" >
              {{ showExams }}
            </div>
          </div>
        </template>
      </el-calendar>
      </div>

      <!-- 试卷列表部分 -->
      <div class="paper-container">
        <div class="wrapper" style="height:800px;">
          <ul class="top">
            <li style="font-size: 20px;">
              <svg-icon icon-class="examsearch" style="font-size: 35px; margin-right: 10px;" />
              试卷列表
            </li>
              <li class="search-li">
                  <el-input
                    placeholder="试卷名称"
                    v-model="listQueryParam.examName">
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                  </el-input>

                <!-- <div class="icon">
                  <input type="text" placeholder="试卷名称" class="search" v-model="listQueryParam.examName">
                  <i class="el-icon-search"></i>
                </div> -->
              </li>
            <li>
              <el-button type="primary" @click="search" size="small">
                <svg-icon icon-class="search" style="font-size: 20px; margin-right: 5px; text-align: center;" />
                搜索
              </el-button>
            </li>
          </ul>
          <ul class="paper" v-loading="loading">
            <li @click="toExamMsg(item)" class="item" v-for="(item, index) in listQueryParam.records" :key="index" :style="{ backgroundImage: item.examavatar ? `url(${item.examavatar})` : 'none' }">
              <div class="image-container">
                <!-- 图片显示区域 -->
              </div>
              <div class="info-container">
                <!-- 文字介绍区域 -->
                <div style="font-size: 22px; color: red;">
                  <i class="iconfont icon-r-paper" style="font-size: 28px;"></i>
                  {{ item.examName }}
                </div>
                <p class="name">{{ item.examName }}-{{ item.remark }}</p>
                <div class="info">
                  <span>考试截止时间：{{ item.endTime }}</span>
                </div>
              </div>
            </li>
          </ul>
          <pagination v-show="total>0"
                      :total="total"
                      :page.sync="listQueryParam.current"
                      :limit.sync="listQueryParam.pageSize"
                      @pagination="getTableDataList"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getList,
  insert,
  update,
  get,
  del,
  getExamDate,
  getStudentDate,
  saveData,
  saveNewData
} from '@/api/ExamStudent/index'
import { getList as getExamavatar } from '@/api/Exam/index'
import Pagination from '@/components/Pagination'
import { tableUtil } from '@/mixins/table'
import { Message } from 'element-ui'
import uploadImg from '@/components/ImageUpload'
import ImgPreview from '@/components/ImgPreview'
import FileUpload from '@/components/FileUpload'

export default {
  mixins: [tableUtil],
  components: {
    FileUpload,
    Pagination, uploadImg, ImgPreview
  },
  data() {
    return {
      showExams: '' ,// 用于存储鼠标悬浮日期的考试名称
      isDataLoaded: false, // 在 data 中声明 isDataLoaded，并初始化为 false
      activeName: 'first',
      value: new Date(), // 日历绑定的值
      loading: false,
      type: localStorage.getItem('examType'),
      listQueryParam: {
        current: 1,
        pageSize: 5
      },
      listQueryParam1: {
        current: 1,
        pageSize: 500
      },
      excelUrl: '',
      dialogVisible: false,
      showExcel: false,
      formData: {},
      rules: {
        examId: [
          { required: true, message: '请选择所属考试', trigger: 'change' }
        ],
        studentId: [
          { required: true, message: '请选择所属学生', trigger: 'change' }
        ]
      },
      examIdOptions: [],
      studentIdOptions: [],
      currentStudent: {},
      images: [
        { src: require('@/assets/title1.jpg'), alt: 'Image 1' },
        { src: require('@/assets/title2.jpg'), alt: 'Image 2' },
        { src: require('@/assets/title3.jpg'), alt: 'Image 3' }
      ],
      currentIndex: 0,
      intervalId: null
    }
  },
  mounted() {
    this.getTableDataList()
    this.loading = true
    this.startAutoPlay()
  },
  beforeDestroy() {
    this.stopAutoPlay()
  },
  methods: {
    isMarked(date) {
      const dateStr = this.formatDate(date);
      const markedDates = this.listQueryParam.records
        .map(record => this.formatDate(new Date(record.endTime)))
        .filter(date => date);

      return markedDates.includes(dateStr);
    },
    getExamsForDate(date) {
    const dateStr = this.formatDate(date);
    console.log("555:",dateStr)
    const exams = this.listQueryParam.records
      // .filter(record => this.formatDate(new Date(record.endTime)) === dateStr)
      .filter(record => {
        const endTime = new Date(record.endTime);
        const formattedEndTime = this.formatDate(endTime);
        console.log("Exam endTime:", formattedEndTime, "Record:", record);
        return formattedEndTime === dateStr;
      })
      .map(record => record.examName);
    console.log("Exams for date:", exams);
    return exams.join(', '); // 将考试名称用逗号连接成字符串
  },
    formatDate(date) {
      if (!date) return '';
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    uploadExcel() {
      this.dialogVisible = true
    },
    saveExcel() {
      if (!this.excelUrl) {
        Message.error('请先上传文件')
        return
      }
      let param = {}
      param.url = this.excelUrl
      param.studentId = localStorage.getItem('examId')
      saveNewData(param).then((res) => {
        this.excelUrl = ''
        Message.success(res.data)
        this.dialogVisible = false
      })
    },
    getTableDataList() {
      if (this.type == 2) {
        this.listQueryParam.studentId = localStorage.getItem('examId');
      }
      this.loading = true;

      getList(this.listQueryParam).then((res) => {
        console.log("接口返回的数据:", res);
        this.listQueryParam.records = res.data.records;
        console.log("获取到的 records 数据:", this.listQueryParam.records);
        this.total = res.data.total;

        getExamavatar(this.listQueryParam1).then((res) => {
          console.log("获取到的 examavatar 数据:", res);
          const examavatarList = res.data.records;
          console.log("123456:",examavatarList);

          this.listQueryParam.records = this.listQueryParam.records.map(record => {
            const matchingExamavatar = examavatarList.find(item => item.id === record.examId);
            return {
              ...record,
              examavatar: matchingExamavatar ? matchingExamavatar.examavatar : '',
              remark: matchingExamavatar ? matchingExamavatar.remark : ''
            };
          });

          console.log("更新后的 this.listQueryParam.records:", this.listQueryParam.records);
          this.loading = false;
          this.isDataLoaded = true; // 数据加载完成后，设置标志变量为 true
        }).catch((error) => {
          console.error("获取 examavatar 数据失败:", error);
          this.loading = false;
        });
      }).catch((error) => {
        console.error("获取列表数据失败:", error);
        this.loading = false;
      });
    },
    updateClick(row) {
      this.dialogTitle = '修改'
      get(row.id).then((res) => {
        this.formData = res.data
        this.addOrUpdateDialogVisible = true
      })
    },
    delByIds(ids) {
      del(ids).then((res) => {
        Message.success('删除成功')
        this.getTableDataList()
      })
    },
    toExamMsg(exam) {
      console.log("传递过去的数据：",exam)
      console.log("传递过去的id：",exam.examId)
      const now = new Date();
      const endTime = new Date(exam.endTime);

      if (now > endTime) {
        this.$message({
          message: "已超过考试作答时间",
          type: "error",
        });
      }else{
        this.$router.push({
            path: "/TakeExam/examMsg",
            query: { examId: exam.examId ,
                    Id:exam.id,
                    takeTime:exam.takeTime},
        });
      }
    },
    saveData() {
      if (this.formData.id) {
        update(this.formData).then((res) => {
          Message.success('修改成功')
          this.addOrUpdateDialogVisible = false
          this.getTableDataList()
        })
      } else {
        insert(this.formData).then((res) => {
          Message.success('添加成功')
          this.addOrUpdateDialogVisible = false
          this.getTableDataList()
        })
      }
    },
    startAutoPlay() {
      this.intervalId = setInterval(() => {
        this.currentIndex = (this.currentIndex + 1) % this.images.length;
      }, 3000);
    },
    stopAutoPlay() {
      clearInterval(this.intervalId);
    },
    prevSlide() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
      } else {
        this.currentIndex = this.images.length - 1;
      }
    },
    nextSlide() {
      if (this.currentIndex < this.images.length - 1) {
        this.currentIndex++;
      } else {
        this.currentIndex = 0;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 2000px;
  margin-left: -180px; /* 向左移动20px */
  margin-right: auto; /* 保持右侧自动对齐 */
}

.title-container {
  margin: 20px;
}

.carousel {
  width: 80%;
  margin: 20px auto;
  position: relative;
  overflow: hidden;
  height: 280px;
}

.carousel-inner {
  display: flex;
  transition: transform 0.5s ease;
}

.carousel-item {
  flex: 0 0 100%;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.carousel-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-control-prev, .carousel-control-next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  border: none;
  padding: 10px;
  cursor: pointer;
}

.carousel-control-prev {
  left: 10px;
}

.carousel-control-next {
  right: 10px;
}

.carousel-control-prev-icon, .carousel-control-next-icon {
  background-image: none;
  font-size: 2rem;
  color: #fff;
}

.carousel-control-prev-icon:after {
  content: '‹';
}

.carousel-control-next-icon:after {
  content: '›';
}

.content-container {
  display: flex;
  width: 100%;
  max-width: 1600px;
  margin: 0 auto;
}

.calendar-container, .paper-container {
  flex: 1;
  margin: 20px;
}

.calendar-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column; /* 确保父容器是垂直排列 */
  margin-top:-70px;
}

.info-container {
  margin-top: 180px; /* 向下移动20px */
  text-align: center;
}

.paper-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.wrapper {
  width: 100%;
  height: 800px;
}

.wrapper  li{
  list-style-type: none;
}

.top {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.top li {
  margin: 0 20px;
}

.search-li {
  margin-left: auto;
}

.search {
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #eee;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
}

.search:hover {
  color: #0195ff;
  border-color: #0195ff;
}

.paper {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

.paper li {
  list-style-type: none;
  width: 380px;
  height: 320px;
  border-radius: 4px;
  padding: 20px 30px;
  border: 1px solid #eee;
  box-shadow: 0 0 4px 2px rgba(217, 222, 234, 0.3);
  transition: all 0.6s ease;
  margin-bottom: 20px;
  cursor: pointer; 
  background-position: center; /* 图片居中 */
  background-size: contain; /* 图片等比缩小 */
  background-repeat: no-repeat; /* 避免图片重复 */
}

.paper li:hover {
  box-shadow: 0 0 4px 2px rgba(140, 193, 248, 0.45);
  transform: scale(1.03);
}

.item .info i {
  margin-right: 5px;
  color: #0195ff;
}

.item .info span {
  margin-right: 14px;
}

.item .info, .item .name {
  font-size: 14px;
  color: #88949b;
}

.pagination {
  padding: 20px 0;
  width: 100%;
  display: flex;
  justify-content: center;
}
.exams-tooltip {
  position: absolute !important;
  top: 100% !important;
  left: 250px !important;
  background: white !important;
  border: 1px solid #ccc !important;
  padding: 5px !important;
  z-index: 100 !important;
  white-space: nowrap !important;
  color: red !important; /* 设置字体颜色为红色 */

}
.calendar-title {
  text-align: center;
  margin-bottom: 20px;
   writing-mode: horizontal-tb; /* 显式设置为水平排列 */
  h2 {
    font-size: 24px;
    color: #333;
    font-weight: bold;
  }
}
.marked {
  background-color: rgba(255, 255, 0, 0.5); /* 红色背景，半透明 */
  height: 70px;
}
</style>